package com.ruoyi.system.contractTemplate.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.system.contractTemplate.domain.PbContractTemplate;
import com.ruoyi.system.contractTemplate.service.IPbContractTemplateService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 合同模板Controller
 * 
 * @author ruoyi
 * @date 2025-04-23
 */
@RestController
@RequestMapping("/contractTemplate/template")
public class PbContractTemplateController extends BaseController
{
    @Autowired
    private IPbContractTemplateService pbContractTemplateService;
    @Autowired
    private ServerConfig serverConfig;

    /**
     * 查询合同模板列表
     */
    @PreAuthorize("@ss.hasPermi('contractTemplate:template:list')")
    @GetMapping("/list")
    public TableDataInfo list(PbContractTemplate pbContractTemplate)
    {
        startPage();
        List<PbContractTemplate> list = pbContractTemplateService.selectPbContractTemplateList(pbContractTemplate);
        return getDataTable(list);
    }

    /**
     * 导出合同模板列表
     */
    @PreAuthorize("@ss.hasPermi('contractTemplate:template:export')")
    @Log(title = "合同模板", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PbContractTemplate pbContractTemplate)
    {
        List<PbContractTemplate> list = pbContractTemplateService.selectPbContractTemplateList(pbContractTemplate);
        ExcelUtil<PbContractTemplate> util = new ExcelUtil<PbContractTemplate>(PbContractTemplate.class);
        util.exportExcel(response, list, "合同模板数据");
    }

    /**
     * 获取合同模板详细信息
     */
    @PreAuthorize("@ss.hasPermi('contractTemplate:template:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(pbContractTemplateService.selectPbContractTemplateById(id));
    }


    /**
     * 修改合同模板
     */
    @PreAuthorize("@ss.hasPermi('contractTemplate:template:edit')")
    @Log(title = "合同模板", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PbContractTemplate pbContractTemplate)
    {
        return toAjax(pbContractTemplateService.updatePbContractTemplate(pbContractTemplate));
    }

    /**
     * 删除合同模板
     */
    @PreAuthorize("@ss.hasPermi('contractTemplate:template:remove')")
    @Log(title = "合同模板", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(pbContractTemplateService.deletePbContractTemplateByIds(ids));
    }

    /**
     * 新增合同模板
     */
    @PostMapping
    public AjaxResult add(@RequestBody PbContractTemplate pbContractTemplate) {
        // 如果未传name，则用文件路径中的文件名（去掉后缀）作为name
        if (StringUtils.isEmpty(pbContractTemplate.getName()) && StringUtils.isNotEmpty(pbContractTemplate.getFilePath())) {
            String fileName = FileUtils.getName(pbContractTemplate.getFilePath()); // 获取文件名（如"紫金项目_20240706155317A001.txt"）
            String nameWithoutExt = fileName.substring(0, fileName.lastIndexOf('.')); // 去掉后缀
            pbContractTemplate.setName(nameWithoutExt);
        }
        return toAjax(pbContractTemplateService.insertPbContractTemplate(pbContractTemplate));
    }


    /**
     * 上传文件接口
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/uploadFile")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径 ,已在配置文件配置D:/ruoyi/uploadPath
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称 . "fileName": "/profile/upload/2024/07/06/紫金项目_20240706155317A001.txt",
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            //这些信息返回给前端之后，
            AjaxResult ajax = AjaxResult.success();
            //"url": "http://localhost:8080/profile/upload/2024/11/07/紫金项目_20240706155317A001.txt
            ajax.put("url", url);
            // "fileName": "/profile/upload/2024/07/06/紫金项目_20240706155317A001.txt",前端传回的也是这个,然后把这个存入数据库
            ajax.put("fileName", fileName);
            //"newFileName": "紫金项目_20240706155317A001.txt",
            ajax.put("newFileName", FileUtils.getName(fileName));
            // "originalFilename": "紫金项目.txt"，用于给前端列表回显
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

}
